package com.xrkj.b2c.controller.bus;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xrkj.b2c.common.Constant;
import com.xrkj.b2c.controller.common.BasicController;
import com.xrkj.b2c.exception.BusinessException;
import com.xrkj.b2c.model.bus.BusOrder;
import com.xrkj.b2c.model.sys.SysCustomer;
import com.xrkj.b2c.model.sys.SysSupplier;
import com.xrkj.b2c.service.bus.BusOrderService;
import com.xrkj.b2c.service.sys.SysAdminService;
import com.xrkj.b2c.service.sys.SysCustomerService;
import com.xrkj.b2c.service.sys.SysSupplierService;
import com.xrkj.b2c.utils.ExcelUtil;
import com.xrkj.b2c.utils.StringUtil;
import com.xrkj.b2c.view.AdminView;

/**
 * 
 * <B>系统名称：</B><BR>
 * <B>模块名称：</B><BR>
 * <B>中文类名：</B>订单控制器<BR>
 * <B>概要说明：</B><BR>
 * 
 * @author （赵子靖）
 * @since 2018年07月15日
 */
@RequestMapping("/order")
@Controller
public class OrderController extends BasicController {

    @Autowired
    private BusOrderService orderService;
    @Autowired
    private SysCustomerService sysCustomerService;
    @Autowired
    protected SysSupplierService supplierService;

    @Autowired
    private SysAdminService sysAdminService;


    /**
     * 
     * <B>方法名称：</B>订单列表<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2018年7月8日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/forwardOrderManager")
    public ModelAndView forwardOrderManager(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("WEB-INF/pages/bus/order/order-to-manager");
    }

    /**
     * 
     * <B>方法名称：</B>获取列表<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2017年10月20日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/orderList")
    @ResponseBody
    public Object orderList(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> ret = new HashMap<String, Object>();
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        Map<String, Object> paramter = new HashMap<String, Object>();
        paramter.put("offset", StringUtil.isEmpty(offset) ? null : Integer.parseInt(offset));
        paramter.put("limit", StringUtil.isEmpty(limit) ? null : Integer.parseInt(limit));
        paramter.put("sellerNicheng", request.getParameter("sellerNicheng"));
        paramter.put("oSupplier", request.getParameter("oSupplier"));
        paramter.put("oTicketNo", request.getParameter("oTicketNo"));
        paramter.put("oName", request.getParameter("oName"));
        paramter.put("oPnr", request.getParameter("oPnr"));
        paramter.put("oNo", request.getParameter("oNo"));
        paramter.put("oIssueDate", request.getParameter("oIssueDate"));
        //判断权限查询相应的数据
        AdminView adminView = (AdminView)request.getSession().getAttribute("admin");
        if(adminView==null){
            throw new BusinessException("登录超时。");
        }
        if(Constant.ROLE_ADMINISTRATIOR_ID.equals(adminView.getRole().getrId())){
            //超级管理员查询所有的订单
            paramter.put("loginId", null);
        }else{
            //其余只能查询自己的订单
            paramter.put("loginId", adminView.getId());
        }
        Integer total = orderService.findOrderTotal(paramter);
        List<BusOrder> orders = new ArrayList<BusOrder>();
        if (total > 0) {
             orders = orderService.findOrderList(paramter);
        }
        
        ret.put("total", total);
        ret.put("rows", orders);
        return ret;
    }


    /**
     * 
     * <B>方法名称：</B>导出订单 Excel表格<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author knn
     * @since 2018年07月09日
     * @return
     */
    @RequestMapping("/orderListDownload")
    @ResponseBody
    public void orderListDownload(HttpServletRequest request, HttpServletResponse response) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        Map<String, Object> paramter = new HashMap<String, Object>();
        paramter.put("offset", StringUtil.isEmpty(offset) ? null : Integer.parseInt(offset));
        paramter.put("limit", StringUtil.isEmpty(limit) ? null : Integer.parseInt(limit));
        paramter.put("sellerNicheng", request.getParameter("sellerNicheng"));
        paramter.put("oSupplier", request.getParameter("oSupplier"));
        paramter.put("oTicketNo", request.getParameter("oTicketNo"));
        paramter.put("oName", request.getParameter("oName"));
        paramter.put("oPnr", request.getParameter("oPnr"));
        paramter.put("oNo", request.getParameter("oNo"));
        paramter.put("oIssueDate", request.getParameter("oIssueDate"));
        //判断权限查询相应的数据
        AdminView adminView = (AdminView)request.getSession().getAttribute("admin");
        if(adminView==null){
            throw new BusinessException("登录超时。");
        }
        if(Constant.ROLE_ADMINISTRATIOR_ID.equals(adminView.getRole().getrId())){
            //超级管理员查询所有的订单
            paramter.put("loginId", null);
        }else{
            //其余只能查询自己的订单
            paramter.put("loginId", adminView.getId());
        }
        List<BusOrder> orderList = orderService.findOrderList(paramter);
        
        if (!CollectionUtils.isEmpty(orderList)) {
            // excel标题
            String[] title ={"订单编号","PNR","乘机人","行程","票号","客户","票证来源","供应商","票面价","后返","税金","结算价","实收价","利润","状态","填单人","录单日期","出单日期","备注"};
            // excel文件名
            String fileName = "订单表" + System.currentTimeMillis() + ".xls";
            // sheet名
            String sheetName = "订单表";
            String content[][] = new String[orderList.size()][title.length];
            for (int i = 0; i < orderList.size(); i++) {
                content[i] = new String[title.length];
                BusOrder obj = orderList.get(i);
                content[i][0] = obj.getoNo(); // 订单编号
                content[i][1] = obj.getoPnr(); // PNR
                content[i][2] = obj.getoName(); // 乘机人
                content[i][3] = obj.getoRoute(); // 行程
                content[i][4] = obj.getoTicketNo(); // 票号
                content[i][5] = obj.getCustomerName(); // 客户
                content[i][6] = obj.getoTicketSource(); // 票证来源
                content[i][7] = obj.getoSupplier(); // 供应商
                content[i][8] = obj.getoTicketPrice()!=null?obj.getoTicketPrice().toString():"0"; // 票面价
                content[i][9] = obj.getoTicketRebate()+""; //后返
                content[i][10] = obj.getoTicketTax()!=null?obj.getoTicketTax().toString():"0"; // 税金
                content[i][11] = obj.getoTicketSettlementPrice()+"";//结算价
                content[i][12] = obj.getoStatus()!=null?obj.getoStatus().toString():"0";//实收价
                content[i][13] = obj.getoTicketProfit()+"";//利润
                String statusStr = "";
                switch (obj.getoStatus()) {
                case 0:
                    statusStr="新增";
                    break;
                case 1:
                    statusStr="出票";
                    break;
                case 2:
                    statusStr="退票";
                    break;
                case 3:
                    statusStr="改期";
                    break;
                case 4:
                    statusStr="废票";
                    break;
                default:
                    break;
                }
                content[i][14] = statusStr; // 订单状态----新增
                content[i][15] = obj.getSellerNicheng();// 销售人员 ------新增
                
                content[i][16] = obj.getoCreateTime()+""; // 订单日期 ------新增
                content[i][17] = new SimpleDateFormat("yyyy-MM-dd").format(obj.getoCreateTime())+""; // 出单日期 ------新增
                content[i][18] = obj.getoRemark()+""; //备注
            }
            // 创建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
            // 响应到客户端
            try {
                this.setResponseHeader(response, fileName);
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            throw new BusinessException("没有匹配到可用的数据。");
        }
    }

    // 发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 
     * <B>方法名称：</B>跳转修改页面<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2018年7月9日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/forwardUpdateOrderPage")
    public ModelAndView forwardUpdateOrderPage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");// 订单Id
        BusOrder order = orderService.selectByPrimaryKey(id);
        request.setAttribute("item", order);
        return new ModelAndView("WEB-INF/pages/bus/order/update-order-dialog");
    }

    /**
     * 修改订单回显
     *
     * @param id id
     * @return 数据
     */
    @RequestMapping("/forwardUpdateOrderPost")
    public ModelAndView findBusOrderById(String id) {

        Map<String, Object> map = new HashMap<>();

        BusOrder busOrder = orderService.selectByPrimaryKey(id);
        map.put("busOrder", busOrder);

        List<SysSupplier> supplierList = supplierService.findSupplierList(null);
        map.put("oSupplierList", supplierList);

        return new ModelAndView("WEB-INF/pages/bus/order/update-order-dialog-new", "item", map);
    }


    /**
     * 修改订单
     * 
     * @param busOrder
     * @return
     */
    @RequestMapping(value = "/updateOrderPost", produces = {"text/html;charset=UTF-8;", "application/json;"})
    @ResponseBody
    public String updateOrderById(BusOrder busOrder) {
        int i = orderService.updateOrder(busOrder);
        if (i > 0) {
            return "修改成功！";
        } else {
            return "修改失败！";
        }
    }

    @RequestMapping(value = "delOrderPost", produces = {"text/html;charset=UTF-8;", "application/json;"})
    @ResponseBody
    public String delOrderById(String id) {
        int i = orderService.deleteOrder(id);
        if (i > 0) {
            return "删除成功！";
        } else {
            return "删除失败！";
        }
    }

    /**
     * 
     * <B>方法名称：</B>批量订单创建<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2018年7月14日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/bathCreateOrderForPnr")
    @ResponseBody
    public Map<String, Object> bathCreateOrderForPnr(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> ret = new HashMap<String, Object>();
        String data = request.getParameter("data");
        if (StringUtil.isEmpty(data)) {
            ret.put("success", false);
            ret.put("msg", "保存失败，待生成订单pnr为空。");
            return ret;
        }
        AdminView adminView = (AdminView)request.getSession().getAttribute("admin");
        if(adminView==null){
            throw new BusinessException("登录超时。");
        }
        if ((orderService.bathCreateOrderForPnr(data,adminView.getId()))) {
            ret.put("success", true);
            ret.put("msg", "保存成功。");
        } else {
            ret.put("success", false);
            ret.put("msg", "保存失败。");
        }
        return ret;
    }



    @RequestMapping("/forwardSelectCustomer")
    public ModelAndView findCustomerList(String search, Integer offset, Integer limit) {

        Map<String, Object> ret = new HashMap<>();
        Map<String, Object> paramter = new HashMap<>();
        paramter.put("offset", offset);
        paramter.put("limit", limit);
        paramter.put("search", search);
        Integer total = sysCustomerService.findCustomerTotal(paramter);
        System.out.println("总条数：" + total);
        List<SysCustomer> customers = new ArrayList<>();
        if (total > 0) {
            customers = sysCustomerService.findCustomerList(paramter);
            if (customers != null && customers.size() > 0) {
                for (SysCustomer busShop : customers) {
                    System.out.println(busShop.toString());
                }
            }
        }
        ret.put("total", total);
        ret.put("rows", customers);

        return new ModelAndView("WEB-INF/pages/bus/order/select-order-customer");
    }

}
